#!/bin/bash -e
# Copyright (C) 2022 Simo Sorce <simo@redhat.com>
# SPDX-License-Identifier: Apache-2.0

source "${TESTSSRCDIR}/helpers.sh"

title PARA "Check we can fetch certificate objects"

ossl '
x509 -in ${CRTURI} -subject -out ${TMPPDIR}/crt-subj.txt'
DATA=$(sed -e 's/\ =\ /=/g' "${TMPPDIR}/crt-subj.txt")
CHECK="subject=O=PKCS11 Provider, CN=My Test Cert"
if [[ ! ${DATA} =~ ${CHECK} ]]; then
    echo "Cert not found looking for ${CHECK}"
    exit 1
fi

ossl '
x509 -in ${ECCRTURI} -subject -out ${TMPPDIR}/eccrt-subj.txt'
DATA=$(sed -e 's/\ =\ /=/g' "${TMPPDIR}/eccrt-subj.txt")
CHECK="subject=O=PKCS11 Provider, CN=My EC Cert"
if [[ ! ${DATA} =~ ${CHECK} ]]; then
    echo "Cert not found looking for ${CHECK}"
    exit 1
fi

title PARA "Use storeutl command to match specific certs via params"

SUBJECTS=("/O=PKCS11 Provider/CN=My Test Cert"
          "/O=PKCS11 Provider/CN=My EC Cert"
          "/CN=My Peer EC Cert"
          "/CN=Issuer")

for subj in "${SUBJECTS[@]}"; do
ossl '
storeutl -certs -subject "${subj}"
                -out ${TMPPDIR}/storeutl-crt-subj.txt
                pkcs11:type=cert'
DATA=$(cat "${TMPPDIR}/storeutl-crt-subj.txt")
if [[ ! ${DATA} =~ "Total found: 1" ]]; then
    echo "Cert not found matching by subject=${subj}"
    exit 1
fi
done

title PARA "Test fetching certificate without PIN in config files"
ORIG_OPENSSL_CONF=${OPENSSL_CONF}
sed "s/^pkcs11-module-token-pin.*$/##nopin/" "${OPENSSL_CONF}" > "${OPENSSL_CONF}.nopin"
OPENSSL_CONF=${OPENSSL_CONF}.nopin
ossl 'x509 -in $CRTURI -subject -out ${TMPPDIR}/crt-subj-nopin.txt'

title PARA "Test fetching certificate via STORE api"
$CHECKER "${TESTBLDDIR}/ccerts" "${CRTURI}" nopin

OPENSSL_CONF=${ORIG_OPENSSL_CONF}
exit 0
